package service

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"nood/app/cache/noodredis"
	"nood/app/model/noodmysql"
	"nood/noodframe/noodlog"
	"nood/noodframe/noodws"
	"time"
)

// 服务层，在这里完成业务逻辑
func TakeService(ctx *gin.Context) {
	noodws.SendToClient(12345, "take", gin.H{"name": "来自http的推送"})
	noodws.SendErrorToClient(12345, "take", 101010, "我出错了")
	noodws.SendErrorAndDataToClient(12345, "take", 101010, "我出错了", gin.H{"name": "来自http的推送的错误code", "age": 10})
	noodws.SendErrorCodeToClient(12345, "take", 101010)
	noodws.BatchSendToClient([]int64{12345}, "take", gin.H{"name": "来自http的批量推送"})
	//设置redis键
	noodredis.Set(ctx.Request.Context(), "text1", "aaa", 60)
	//根据键获取redis中的信息
	text1, err := noodredis.Get(ctx.Request.Context(), "text1")
	noodlog.Debug("Take noodredis.Get", zap.Any("text1", text1), zap.Any("err", err))
	//redis订阅一个频道
	go TestSubscribe(ctx.Request.Context(), "channel1")
	//休眠1秒
	time.Sleep(time.Second)
	//给订阅的频道发送信息
	err1 := noodredis.Publish(ctx.Request.Context(), "channel1", "发布信息")
	noodlog.Debug("Take Publish", zap.Any("err1", err1))
	//使用mysql
	noodmysql.QueryCase(nil)

	//使用事务
	//tx := model.Mysql(nil).Begin()
	//_,err = noodmysql.QueryCase(tx)
	////遇到错误时回滚事务
	//if err != nil {
	//	tx.Rollback()
	//}
	//_,err = noodmysql.QueryCase2(tx)
	//if err != nil {
	//	tx.Rollback()
	//}
	//// 否则，提交事务
	//tx.Commit()

}

func TestSubscribe(ctx context.Context, channels string) {
	sub, ch := noodredis.Subscribe(ctx, channels)
	defer sub.Close()
	for msg := range ch {
		noodlog.Debug("TestSubscribe", zap.Any("msg", msg))
	}
}
